﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MockCommon;
using MockDataTransferObject;
using MockBusiness;
using System.Data;
using System.Collections.ObjectModel;
using System.Globalization;

namespace Presentation.AdminPresentation
{
    public partial class ApproveTimesheet : System.Web.UI.Page
    {
        private MessageBusiness _messageBusiness;
        private TimesheetBusiness _timesheetBusiness;
        private TimesheetStatusBusiness _timesheetStatusBusiness;
        private ReasonBusiness _reasonBusiness;
        private Label _warningLabel;
        private Label _errorLabel;
        private Label _successLabel;
        private ListView _timesheetListView;
        private Button _saveButton;

        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                _messageBusiness = MessageBusiness.RetrieveInstance();
                _timesheetBusiness = TimesheetBusiness.RetrieveInstance();
                _timesheetStatusBusiness = TimesheetStatusBusiness.RetrieveInstance();
                _reasonBusiness = ReasonBusiness.RetrieveInstance();
                _warningLabel = (Label)Master.FindControl("WarningLabel");
                _errorLabel = (Label)Master.FindControl("ErrorLabel");
                _successLabel = (Label)Master.FindControl("SuccessLabel");
                _timesheetListView = (ListView)TimesheetControl.FindControl("TimesheetListView");
                _saveButton = (Button)TimesheetControl.FindControl("SaveButton");
                _saveButton.Click += new EventHandler(SaveButton_Click);
            }
            catch (MockException exception)
            {
                Application["error"] = exception;
                Response.Redirect("../Error.aspx");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user"] != null && Session["user"] is User)
            {
                User user = (User)Session["user"];
                if (user.Role.RoleName != "Admin")
                {
                    Server.Transfer("../NotAuthorized.aspx");
                }
            }
            else
            {
                Response.Redirect("../LogOn.aspx");
            }
            if (IsPostBack)
            {
                _warningLabel.Text = "";
                _errorLabel.Text = "";
                _successLabel.Text = "";
            }
        }

        protected void BindingButton_Click(object sender, EventArgs e)
        {
            if (Loading())
            {
                ApproveTimesheetPanel.Visible = true;
            }
            else
            {
                _errorLabel.Text = "Load timesheets failed!";
                ApproveTimesheetPanel.Visible = false;
            }
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (ListTimesheetId.Value != null && ListStatus.Value != null && ListReason.Value != null)
                {
                    string[] timesheetIds = ListTimesheetId.Value.Split(new char[] { '\n', '\r' });
                    string[] statuses = ListStatus.Value.Split(new char[] { '\n', '\r' });
                    string[] reasons = ListReason.Value.Split(new char[] { '\n', '\r' });
                    MockDataTransferObject.Timesheet timesheet;
                    TimesheetStatus timesheetStatus;
                    Reason reason;
                    for (int i = 0; i < statuses.Length; i++)
                    {
                        reason = null;
                        timesheet = null;
                        bool isValid = false;
                        if (statuses[i] == "1")
                        {
                            timesheet = new MockDataTransferObject.Timesheet();
                            timesheetStatus = _timesheetStatusBusiness.GetByStatusName("Approved");
                            timesheet = _timesheetBusiness.GetById(timesheetIds[i]);
                            timesheet.Status = timesheetStatus;
                            isValid = true;
                        }
                        else if (statuses[i] == "2")
                        {
                            timesheet = new MockDataTransferObject.Timesheet();
                            timesheetStatus = _timesheetStatusBusiness.GetByStatusName("Rejected");
                            timesheet = _timesheetBusiness.GetById(timesheetIds[i]);
                            timesheet.Status = timesheetStatus;
                            isValid = true;

                            reason = new Reason();
                            reason.ReasonId = Guid.NewGuid();
                            reason.ReasonText = reasons[i];
                            reason.ReasonDate = DateTime.Now;
                            reason.Timesheet = timesheet;
                            isValid = true;
                        }
                        if (isValid)
                        {
                            if (timesheet != null)
                            {
                                _timesheetBusiness.Update(timesheet);
                                Notify(timesheet, reason);
                            }
                            if (reason != null)
                            {
                                _reasonBusiness.Create(reason);
                            }
                        }
                    }
                }
                Loading();
                _successLabel.Text = "Update successfully";
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (ArgumentException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (FormatException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        private void Notify(MockDataTransferObject.Timesheet timesheet, Reason reason)
        {
            User fromUser = Session["user"] as User;
            string from = String.Format(CultureInfo.CurrentCulture, "{0}({1})", fromUser.UserName, timesheet.Contract.Client.User.UserName);
            User toUser = timesheet.Contract.Contractor.User;
            Message message = new Message();
            string action = timesheet.Status.StatusName.ToLower(CultureInfo.CurrentCulture);
            string reasonText = reason != null ? "Reason: <b>" + reason.ReasonText + "</b><br/>" : "";
            string content = @"Dear <b>{0}</b>.<br/> 
                               Your timesheet was <b>{1}</b> by <b>{2}</b> at <b>{3}</b>.<br/>
                               {4}
                               Some brief of your timesheet as below:<br/>
                               <div class=""contentMail"">
                               -TimesheetDate: <b>{5}</b>.<br/>
                               -Title: <b>{6}</b>.<br/>
                               -Description: <b>{7}</b>.<br/>
                               -Working time: <b>{8}</b>.<br/>
                               </div><br/>
                               If have any question, please contact to your client!<br/><br/>
                               <b>CMS AutoMailer.</b><br/>
                               <b>&</b>
                               <b>Best Regards!</b>";
            message.MessageId = Guid.NewGuid();
            message.From = fromUser;
            message.To = toUser;
            message.Title = String.Format(CultureInfo.CurrentCulture, "<b>{0}</b> has {1} your timesheet", from, action);
            message.Content = String.Format(CultureInfo.CurrentCulture, content, toUser.UserName, action, from, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss", CultureInfo.CurrentCulture), reasonText, timesheet.TimesheetDate, timesheet.Title, timesheet.Description, timesheet.WorkingTime);
            message.IsRead = false;
            message.IsReceive = false;
            message.SendDate = DateTime.Now;
            _messageBusiness.Insert(message);
        }

        private bool Loading()
        {
            try
            {
                string username = UserNameTextBox.Text;         
                Collection<MockDataTransferObject.Timesheet> timesheets = _timesheetBusiness.GetAllPendingTimesheetByClientUserName(username);
                if (timesheets.Count == 0)
                {
                    return false;
                }
                _timesheetListView.DataSource = timesheets;
                _timesheetListView.DataBind();
                return true;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
                return false;
            }
        }
    }
}